package logger

import (
	"github.com/gin-gonic/gin"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/sirupsen/logrus"
	"io"
	"iot-base/auth/config"
	"os"
	"path"
	"time"
)

var (
	Log         *logrus.Logger
	logFilePath = "../logs"
)

func init() {
	Log = logrus.New()
	// 设置为json格式的日志
	Log.Formatter = &logrus.JSONFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	}
	fileName := path.Join(logFilePath, config.Conf.Logs.LogName)
	// 线上模式，控制台不会打印信息
	//gin.SetMode(gin.ReleaseMode)
	// gin框架自己记录的日志也会输出
	//gin.DefaultWriter = Log.Out
	level := config.Conf.Logs.Level
	switch level {
	case "debug":
		Log.Level = logrus.DebugLevel
		Log.SetOutput(os.Stderr)
	case "info":
		Log.Level = logrus.InfoLevel
	case "warn":
		Log.Level = logrus.WarnLevel
	case "error":
		Log.Level = logrus.ErrorLevel
	default:
		Log.Level = logrus.InfoLevel
	}
	// 设置 rotatelogs
	logWriter, _ := rotatelogs.New(
		// 分割后的文件名称
		fileName+".%Y%m%d.log",
		// 生成软链，指向最新日志文件
		//rotatelogs.WithLinkName(fileName),
		// 设置最大保存时间(3天)
		rotatelogs.WithMaxAge(3*24*time.Hour),
		// 设置日志切割时间间隔(1天)
		rotatelogs.WithRotationTime(24*time.Hour),
	)
	// Gin日志重定向
	gin.DisableConsoleColor()                                //不需要颜色
	gin.DefaultWriter = io.MultiWriter(os.Stdout, logWriter) //os.Stdout
	Log.SetOutput(logWriter)
}
